import javax.swing.tree.TreeNode;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2024-02-03
 * Time:21:59
 */
public class LevelOrder1 {
    class TreeNode {
        int val;
        LevelOrder.TreeNode left;
        LevelOrder.TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, LevelOrder.TreeNode left, LevelOrder.TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

    }

    //Stack<TreeNode> stack = new Stack<>();
    Queue<TreeNode> queue = new LinkedList<>();

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if(root == null) {
            return new ArrayList<List<Integer>>();
        }
        List<List<Integer>> ret = new ArrayList<>();

        queue.offer(root);
        TreeNode cur = root;

        while(!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            TreeNode top = queue.poll();
            int size = queue.size();
            while(size > 0) {
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }

                list.add(top.val);
                size--;
            }
            ret.add(list);
        }
        return ret;
    }
}
